import {Singleton} from "ts.di";
import {SMSService} from "../SMS/SMSService";
import {Hash} from "../Core/Hash/Hash";
/**
 * Created by Weizehua on 2017/1/23.
 */

export interface CaptchaResponse {
    success: boolean,
    captchaHash?: string,
    expiredDate?: Date,
    signature?: string
    reason?: string;
}

@Singleton()
export class CaptchaService {
    constructor(private hasher: Hash, private smsService: SMSService) {
    }

    async sendCaptcha(phone: string, availableMinutes: number = 3): Promise<CaptchaResponse> {
        let res = await this.smsService.sendCaptcha(phone, availableMinutes);
        if (res.success) {
            let captcha = res.captcha;
            let expiredDate = new Date(Number(new Date()) + 1000 * 60 * availableMinutes);
            return {
                success: true,
                captchaDigest: await this.hasher.digestCaptcha(captcha, phone, expiredDate),
                expiredDate: expiredDate,
                signature: await this.hasher.signCaptcha(captcha, expiredDate)
            }
        }
        else return {
            success: false,
            reason: res.reason
        }
    }

    async validateCaptcha(phone: string, captcha: string, info: CaptchaResponse): Promise<boolean> {
        // captcha is not expired
        if (new Date() > info.expiredDate)
            return false;

        // captcha is correct
        let signature = await this.hasher.signCaptcha(captcha, info.expiredDate);
        if (info.signature !== signature)
            return false;

        // captcha is not used
        return this.smsService.validateCaptcha(phone, captcha);
    }
}
